package com.waimai.mobile.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.waimai.mobile.R;
import com.waimai.mobile.api.WaiMaiServer;
import com.waimai.mobile.api.entity.Food;
import com.waimai.mobile.api.entity.Order;
import com.waimai.mobile.api.entity.OrderFood;
import com.waimai.mobile.api.entity.Restaurant;
import com.waimai.mobile.api.model.ResponseModel;
import com.waimai.mobile.ui.WaiMaiApp;
import com.waimai.mobile.ui.activity.OrderConfirmActivity_;
import com.waimai.mobile.ui.activity.RestaurantActivity;
import com.waimai.mobile.ui.activity.RestaurantActivity_;
import com.waimai.mobile.ui.adapter.FoodItemAdapter;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import se.emilsjolander.stickylistheaders.ExpandableStickyListHeadersListView;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

/**
 * Created by lin on 2015/5/29.
 */

@EFragment(R.layout.fragment_restaurant_order)
public class RestaurantOrderFragment extends Fragment {

    public static final int REQUEST_ORDER_CONFIRM = 1;

    public static final int RESULT_RESTAURANT_NOT_EXTIST = 6;
    public static final int RESULT_RESTAURANT_CHANGED = 7;

    public Restaurant restaurant;

    public Order order;

    @App
    public WaiMaiApp app;

    @RestService
    public WaiMaiServer server;

    @Bean
    public FoodItemAdapter adapter;

    @ViewById
    public TextView mentionMsgTv;

    @ViewById
    public TextView totalPriceTv;

    @ViewById
    public Button toOrderConfirmBtn;

    @ViewById(R.id.foodLv)
    public ExpandableStickyListHeadersListView foodLv;

    @AfterViews
    public void afterViews(){
        order = new Order();
        restaurant = ((RestaurantActivity) getActivity()).restaurant;
        order.setRestaurant(restaurant);

        if(restaurant.getRest()){
            mentionMsgTv.setVisibility(View.VISIBLE);
            mentionMsgTv.setText("餐厅休息中，暂不接单");
            foodLv.setVisibility(View.GONE);
            mentionMsgTv.setClickable(false);
            return ;
        }

        foodLv.setOnHeaderClickListener(new StickyListHeadersListView.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId, boolean currentlySticky) {
                if (foodLv.isHeaderCollapsed(headerId)) {
                    foodLv.expand(headerId);
                } else {
                    foodLv.collapse(headerId);
                }
            }
        });
        adapter.setListener(new FoodItemAdapter.OnOrderFoodsChangeListener() {
            @Override
            public void onOrderFoodsChanged(List<OrderFood> orderFoods) {
                float totalPrice = getTotalPrice(orderFoods);
                order.setTotalPrice(totalPrice);
                order.setOrderfoods(orderFoods);
                totalPriceTv.setText(totalPrice + "");
                if(totalPrice >= restaurant.getSendPrice().floatValue()){
                    toOrderConfirmBtn.setText("选好了");
                    toOrderConfirmBtn.setEnabled(true);
                }else{
                    toOrderConfirmBtn.setText("差"+(restaurant.getSendPrice()-totalPrice)+"元起送");
                    toOrderConfirmBtn.setEnabled(false);
                }
            }
        });

        loading();
        loadFoods(restaurant.getRestaurantId());
    }

    @Background
    public void loadFoods(Integer restaurantId){
        ResponseModel<List<Food>> model;
        try{
            model = server.foods(restaurantId);
            if(model != null){
                switch (model.getStatus().getStatusCode()) {
                    case ResponseModel.STATUS_GET_DATA_SUCCESS:
                        loadedSuccess(model.getData());
                        break;
                    case ResponseModel.STATUS_GET_DATA_NONE:
                        loadNoneData();
                        break;
                    case ResponseModel.STATUS_SERVER_ERROR:
                        serverError();
                        break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            netError();
        }
    }

    @UiThread
    public void loadedSuccess(List<Food> foods){
        adapter.setFoods(foods);
        foodLv.setAdapter(adapter);
        foodLv.setVisibility(View.VISIBLE);
        mentionMsgTv.setVisibility(View.GONE);
        if(restaurant.getSendPrice() == 0){
            toOrderConfirmBtn.setText("选好了");
            toOrderConfirmBtn.setEnabled(true);
        }else {
            toOrderConfirmBtn.setText("差" + (restaurant.getSendPrice()) + "元起送");
            toOrderConfirmBtn.setEnabled(false);
        }
    }

    @UiThread
    public void loading(){
        foodLv.setVisibility(View.GONE);
        mentionMsgTv.setText("正在加载...");
        mentionMsgTv.setVisibility(View.VISIBLE);
        mentionMsgTv.setClickable(false);
    }

    @UiThread
    public void loadNoneData() {
        foodLv.setVisibility(View.GONE);
        mentionMsgTv.setText("该餐厅还没有菜品啊，点击刷新试试");
        mentionMsgTv.setVisibility(View.VISIBLE);
        mentionMsgTv.setClickable(true);
    }

    @UiThread
    public void netError(){
        foodLv.setVisibility(View.GONE);
        mentionMsgTv.setText("网络错误，点击重试");
        mentionMsgTv.setVisibility(View.VISIBLE);
        mentionMsgTv.setClickable(true);
    }

    @UiThread
    public void serverError() {
        foodLv.setVisibility(View.GONE);
        mentionMsgTv.setText("服务器异常，点击重试");
        mentionMsgTv.setVisibility(View.VISIBLE);
        mentionMsgTv.setClickable(true);
    }

    @Click(R.id.mentionMsgTv)
    public void mentionMsgTvClick(View v){
        loading();
        loadFoods(restaurant.getRestaurantId());
    }

    public float getTotalPrice(List<OrderFood> orderFoods){
        float totalPrice = 0;
        for(OrderFood orderFood : orderFoods){
            float temp = orderFood.getFoodPrice() * orderFood.getFoodAmount();
            totalPrice = totalPrice + temp;
        }
        return totalPrice;
    }

    @Click(R.id.toOrderConfirmBtn)
    public void toOrderConfirmBtnClick(View v){
        checkOrder(order);
        Intent intent = new Intent(getActivity(), OrderConfirmActivity_.class);
        intent.putExtra("order", order);
        startActivityForResult(intent, REQUEST_ORDER_CONFIRM);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (resultCode) {
            case RESULT_RESTAURANT_CHANGED:
                ((RestaurantActivity)getActivity()).refreshData();
                break;

            case RESULT_RESTAURANT_NOT_EXTIST:
                ((RestaurantActivity)getActivity()).onBackPressed();
                break;
        }
    }

    public void checkOrder(Order order){
        order.setUser(app.getUser());
        order.setDeliveryPrice(order.getRestaurant().getDeliveryPrice());
        for(Iterator<OrderFood> iterator = order.getOrderfoods().iterator();iterator.hasNext();){
            if (iterator.next().getFoodAmount() == 0){
                iterator.remove();
            }
        }
    }
}